<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="searchBox searchInputWidth"
        style="padding-bottom: 0; position: relative"
      >
        <el-form :inline="true" :model="filterField" ref="accountForm">
          <el-col :lg="8" :xl="6">
            <el-form-item label="巡查类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.type"
                placeholder="请选择"
                clearable
              >
                <el-option label="日常巡查" value="DAILY"></el-option>
                <el-option label="专项巡查" value="SPECIAL"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="单位类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.fieldType"
                placeholder="请选择"
                clearable
              >
                <el-option label="非建领域" value="NC"></el-option>
                <el-option label="建设领域" value="CS"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务批次" class="row-padding-bottom">
                <el-input
                  placeholder="请输入任务批次"
                  clearable
                  v-model="filterField.jobBatchStr"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务编号" class="row-padding-bottom">
                <el-input
                  placeholder="请输入任务编号"
                  clearable
                  v-model="filterField.jobNumber"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="单位名称" class="row-padding-bottom">
                <el-input
                  placeholder="请输入单位名称"
                  clearable
                  v-model="filterField.unitName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务人员" class="row-padding-bottom">
                <el-input
                  placeholder="请输入任务人员"
                  clearable
                  v-model="filterField.jobUserName"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务状态" class="row-padding-bottom">
                <el-select
                  v-model="filterField.status"
                  placeholder="请选择"
                  clearable
                >
                  <el-option label="进行中" value="GOING"></el-option>
                  <el-option label="已完成" value="COMPLETED"></el-option>
                  <el-option label="逾期完成" value="OVER"></el-option>
                  <el-option label="未完成" value="INCOMPLETE"></el-option>
                  <el-option label="已撤销" value="REVOKED"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务模式" class="row-padding-bottom">
                <el-select
                  v-model="filterField.jobMothed"
                  placeholder="请选择"
                  clearable
                >
                  <el-option label="人工指派" value="MANUAL"></el-option>
                  <el-option label="双随机" value="RANDOM"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="截止日期" class="row-padding-bottom">
                <el-date-picker
                  v-model="dateTime"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item>
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <!-- 列表 -->
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="iconfont icondaochu"
            @click="toExport"
          >
            <span class="opetareText">导出</span>
          </el-button>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="iconfont icontianjia"
            @click="toAdd"
          >
            <span class="opetareText">创建任务</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="jobBatch"
            label="任务批次"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="jobNumber"
            label="任务编号"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            prop="typeDesc"
            label="巡查类型"
            :formatter="formatTd"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="fieldTypeDesc"
            label="单位类型"
            :formatter="formatTd"
            min-width="120"
          ></el-table-column>
          <!-- <el-table-column align="center" prop="companyName" label="巡查单位名称" :formatter=formatTd></el-table-column> -->
          <el-table-column label="巡查单位名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="jobUserName" label="任务人员" :formatter=formatTd></el-table-column> -->
          <el-table-column label="任务人员" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.jobUserName"
                :columnName="'jobUserName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="statusDesc"
            label="任务状态"
            :formatter="formatTd"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="endDate"
            label="截止日期"
            sortable="custom"
            :formatter="formatTd"
            min-width="160"
          ></el-table-column>
          <el-table-column
            prop="jobMothedDesc"
            label="任务模式"
            :formatter="formatTd"
            min-width="120"
          ></el-table-column>
          <el-table-column
            align="left"
            label="操作"
            width="180px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="toDetail(scope.row)"
                v-show="isShowDetail"
                >查看</el-link
              >
              <div v-show="isShowUpdate" style="display: inline-block">
                <el-link
                  v-if="
                    scope.row.status == 'GOING' ||
                    scope.row.status == 'INCOMPLETE'
                  "
                  type="primary"
                  @click="toEdit(scope.row)"
                  >编辑</el-link
                >
              </div>
              <el-link
                v-if="scope.row.status == 'GOING' && isShowUpdate"
                type="primary"
                @click="toRevoked(scope.row)"
                >撤销</el-link
              >
              <el-link
                v-if="scope.row.status == 'REVOKED' && isShowDelete"
                type="primary"
                @click="toDel(scope.row)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="640px"
      :modal-append-to-body="false"
    >
      <el-form
        :model="dialogForm"
        ref="dialogForm"
        :rules="dialogRules"
        style="padding-top: 8px"
      >
        <el-form-item
          label="任务人员："
          :label-width="formLabelWidth"
          prop="jobUserIds"
        >
          <el-select
            multiple
            clearable
            filterable
            remote
            v-model="dialogForm.jobUserIds"
            :loading="empSearchLoading"
            :multiple-limit="20"
            placeholder="请选择(可多选)"
            :remote-method="remoteMethod"
            class="mWidth"
          >
            <el-option
              v-for="(item, index) of empList"
              :key="index"
              :label="item.nickname + '(' + item.username + ')'"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="任务期限："
          :label-width="formLabelWidth"
          prop="endDate"
        >
          <el-date-picker
            v-model="dialogForm.endDate"
            value-format="yyyy-MM-dd"
            :picker-options="expireTimeOption"
            type="date"
            class="mWidth"
            placeholder="请选择"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="toSave"
          class="save"
          :loading="canSave"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'

export default {
  name: 'myCreateTaskList',
  data() {
    return {
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
      requestUrl: 'api-gov/ipqcjob/expand/joblist',
      loading: true,
      isShow: false,
      tableData: [], //表格数据
      advanced: false,
      dateTime: '',
      filterField: {
        type: '', //巡查类型
        fieldType: '', //领域类型
        jobBatchStr: '', //任务批次
        jobNumber: '', //任务编号
        unitName: '', //单位名称
        jobUserName: '', //任务人员名称
        jobMothed: '', //任务模式
        startDateStr: '', //截止开始日期
        endDateStr: '', //截止结束日期
        status: '', //任务状态
        parameterType: 'create',
      },
      pageSize: 20,
      pageNo: 1,
      dialogVisible: false,
      formLabelWidth: '120px',
      dialogForm: {
        id: '',
        jobUserIds: '',
        endDate: '',
      },
      dialogRules: {
        jobUserIds: [
          { required: true, message: '请选择任务人员', trigger: 'change' },
        ],
        endDate: [
          { required: true, message: '请选择任务期限', trigger: 'change' },
        ],
      },
      canSave: false,
      empList: [],
      empSearchLoading: false,
      isShowDetail: '',
      isShowUpdate: '',
      isShowDelete: '',
      advanced: false,
      hiddleToolBar: false,
      tableHeight: null,
    }
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('patrolTaskList:detail') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('patrolTaskList:update') > -1
    this.isShowDelete =
      this.$store.state.buttonLimitsArr.indexOf('patrolTaskList:delete') > -1
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }
      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  activated() {
    // this.getEventType();
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //列表查询
    searchTable() {
      if (this.dateTime) {
        this.filterField.startDateStr = this.dateTime[0]
        this.filterField.endDateStr = this.dateTime[1]
      } else {
        this.filterField.startDateStr = ''
        this.filterField.endDateStr = ''
      }
      this.pageSize = 20
      this.pageNo = 1
      this.$refs.pagination.getTableListData()
    },
    toDetail(row) {
      this.$router.push({
        path: '/home/patrolTask/taskDetail',
        name: 'taskDetail',
        query: {
          taskId: row.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/patrolTask/patrolTaskList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toEdit(row) {
      this.getEmpList('')
      this.dialogVisible = true
      this.$nextTick(function () {
        this.$refs.dialogForm.resetFields()
      })
      this.dialogForm.id = row.id
    },
    toSave() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.canSave = true
          this.axios({
            method: 'post',
            url: 'api-gov/ipqcjob/expand/edit',
            data: {
              id: this.dialogForm.id,
              jobUserIds: this.dialogForm.jobUserIds.toString(),
              endDate: this.dialogForm.endDate,
            },
          })
            .then((response) => {
              this.canSave = false
              if (!response.data.hasError) {
                this.$message({
                  type: 'success',
                  message: '保存成功',
                })
                this.dialogVisible = false
                this.$refs.pagination.getTableListData()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.errorMsg,
                })
              }
            })
            .catch((error) => {})
        } else {
          return false
        }
      })
    },
    toRevoked(row) {
      this.$confirm('确认撤销该任务吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.revoked(row.id)
        })
        .catch(() => {})
    },
    revoked(id) {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqcjob/expand/editstatus',
        data: {
          ids: id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '撤销成功',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {})
    },
    toDel(row) {
      this.$confirm('确认删除该任务吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.delTemplate(row.id)
        })
        .catch(() => {})
    },
    delTemplate(id) {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqcjob/expand/delbyid',
        data: {
          id: id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '删除成功',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {})
    },
    toExport() {
      if (this.tableData.length > 0) {
        if (this.filterField.startDateStr == undefined) {
          this.filterField.startDateStr = ''
          this.filterField.endDateStr = ''
        }
        window.location.href =
          common.commonApi +
          'api-gov/ipqcjob/expand/export?type=' +
          this.filterField.type +
          '&fieldType=' +
          this.filterField.fieldType +
          '&jobBatch=' +
          this.filterField.jobBatchStr +
          '&jobNumber=' +
          this.filterField.jobNumber +
          '&unitName=' +
          this.filterField.unitName +
          '&jobUserName=' +
          this.filterField.jobUserName +
          '&jobMothed=' +
          this.filterField.jobMothed +
          '&status=' +
          this.filterField.status +
          '&startDateStr=' +
          this.filterField.startDateStr +
          '&endDateStr=' +
          this.filterField.endDateStr +
          '&parameterType=' +
          this.filterField.parameterType +
          '&sortField=' +
          this.filterField.sortField +
          '&sort=' +
          this.filterField.sort +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'error',
          message: '无数据导出',
        })
      }
    },
    toAdd() {
      this.$router.push({
        path: '/home/inspectionTask/addInspectionTask',
        name: 'addInspectionTask',
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/patrolTask/patrolTaskList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },

    remoteMethod(query) {
      if (query !== '') {
        this.empSearchLoading = true
        this.getEmpList(query)
      } else {
        this.getEmpList()
      }
    },
    getEmpList(nickName) {
      this.axios({
        method: 'get',
        url: 'api-u/users/usersbyname?nickName=' + nickName,
      })
        .then((response) => {
          this.empSearchLoading = false
          if (!response.data.hasError) {
            this.empList = response.data.result
          }
        })
        .catch((error) => {})
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 214

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.mainCon {
  top: 198px;
}
.selectWidth {
  width: 100%;
}
@import '../../../static/css/filterArea.less';
</style>
